package com.ymdx.action;

import com.google.zxing.WriterException;
import com.opensymphony.xwork2.ModelDriven;
import com.ymdx.entity.Product;
import com.ymdx.entity.User;
import com.ymdx.service.ProductService;
import com.ymdx.service.UserService;
import com.ymdx.util.Page;
import com.ymdx.util.tool.BeanCopyUtil;
import com.ymdx.util.tool.DateUtils;
import com.ymdx.util.zxing.QRCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 作品信息
 * Created by yangliwei on 2017/8/16.
 */
public class ProductAction extends GenericActionSupport implements ModelDriven<Product> {
    private Product product;
    @Resource
    private ProductService productService;

    @Resource
    private UserService userService;

    private Page<Product> page;
    private Integer pageSize = 9;
    private Integer pageNo = 1;

    /**
     * 管理员 作品分页
     * 用户ID  作品上传类型 作者信息 名字 是否展示
     *
     * @return
     */
    @Action(value = "/admin/product/page", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "page",
            "includeProperties", "pageNo,pageSize,totalCount,result\\[\\d+\\]\\.id,result\\[\\d+\\]\\.name,result\\[\\d+\\]\\.author,result\\[\\d+\\]\\.type,result\\[\\d+\\]\\.showProduct,result\\[\\d+\\]\\.showOrder,result\\[\\d+\\]\\.createTime"
    })})
    public String adminPage() {
        String author = product.getAuthor();
        Long authorId = product.getAuthorId();
        Integer type = product.getType();
        String name = product.getName();
        Integer show = product.getShowProduct();
        Map<String, Object> args = new HashMap<>();
        if (StringUtils.isNotBlank(author)) {
            args.put("author", author);
        }
        if (StringUtils.isNotBlank(name)) {
            args.put("name", name);
        }
        if (authorId != null) {
            args.put("authorId", authorId);
        }
        if (type != null) {
            args.put("type", type);
        }
        if (show != null) {
            args.put("showProduct", show);
        }
        if (page == null) {
            page = new Page<>();
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
        }
        productService.page(page, args);

        Collections.sort(page.getResult(), new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getShowOrder()-o2.getShowOrder();
            }
        });
        responseTool.setStatus(1);
        responseTool.setData(page);
        return SUCCESS;
    }


    /**
     * 管理员 作品上线与下线
     *
     * @return
     */
    @Action(value = "/admin/product/up", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String up() {
        Long id = product.getId();
        Integer show = product.getShowProduct();
        if (id == null || show == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Product oldProduct = productService.getById(Product.class, id);
        if (oldProduct == null) {
            responseTool.setStatus(0);
            responseTool.setCode("product_not_exist");
            return SUCCESS;
        }
        oldProduct.setShowProduct(show);
        productService.save(oldProduct);
        responseTool.setStatus(1);
        responseTool.setData(oldProduct.getId());


        return SUCCESS;
    }

    /**
     * 管理员作品删除
     *
     * @return
     */
    @Action(value = "/admin/product/delete", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String delete() {
        Long id = product.getId();
        if (id == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Product oldProduct = productService.getById(Product.class, id);
        if (oldProduct == null) {
            responseTool.setStatus(0);
            responseTool.setCode("product_not_exist");
            return SUCCESS;
        }
        productService.delete(oldProduct);
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }

    /**
     * 管理员 获取一条数据 用于编辑
     */
    @Action(value = "/admin/product/detail", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id,data\\.name,data\\.author,data\\.introduction,data\\.sbimage,data\\.sburl,data\\.ewmUrl,data\\.createTime,data\\.showProduct,data\\.showOrder"
    })})
    public String adminDetail() {
        Long id = product.getId();
        if (id == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Product oldProduct = productService.getById(Product.class, id);
        if (oldProduct == null) {
            responseTool.setStatus(0);
            responseTool.setCode("product_not_exist");
            return SUCCESS;
        }
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }


    /**
     * 管理员作品保存
     * 这里需要提供排序
     *
     * @return
     */
    @Action(value = "/admin/product/save", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String adminSave() {
        Long id = product.getId();

        //去除前端传过来的连接的"前缀引号
        product.setSbimage(product.getSbimage().replace("\"",""));
        product.setSburl(product.getSburl().replace("\"",""));

        Product oldProduct = null;
        Boolean flag = false;
        if (id != null) {
            oldProduct = productService.getById(Product.class, id);
            if(!oldProduct.getSburl().equals(product.getSburl())){
                flag = true;
            }
        }
        if (oldProduct == null) {
            oldProduct = new Product();
            oldProduct.setCreateTime(new Date());
            //设置默认值
            oldProduct.setType(1);
            oldProduct.setShowProduct(0);
            oldProduct.setShowOrder(1);
            oldProduct.setAuthorId(0L);
            flag = true;
        }
        BeanCopyUtil.copyProperties(product, oldProduct, true);
        if(flag){
            createQRCode(oldProduct);
        }
        productService.save(oldProduct);
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }

    /**
     * 主页显示的作品
     *
     * @return
     */
    @Action(value = "/product/show", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "page",
            "includeProperties", "pageNo,pageSize,totalCount,result\\[\\d+\\]\\.id,result\\[\\d+\\]\\.name,result\\[\\d+\\]\\.author,result\\[\\d+\\]\\.introduction,result\\[\\d+\\]\\.sbimage"
    })})
    public String show() {
        Map<String, Object> args = new HashMap<>();
        args.put("showProduct", new Integer(1));
        if (page == null) {
            page = new Page<>();
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
        }
        productService.page(page, args);
        Collections.sort(page.getResult(), new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getShowOrder()-o2.getShowOrder();
            }
        });
        responseTool.setStatus(1);
        responseTool.setData(page);
        return SUCCESS;
    }

    /**
     * 主页作品展示
     */
    @Action(value = "/product/detail", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id,data\\.name,data\\.author,data\\.introduction,data\\.sbimage,data\\.sburl,data\\.ewmUrl,data\\.createTime"
    })})
    public String showDetail() {
        Long id = product.getId();
        if (id == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Product oldProduct = productService.getById(Product.class, id);
        if (oldProduct == null||oldProduct.getShowProduct()==0) {
            responseTool.setStatus(0);
            responseTool.setCode("product_not_exist");
            return SUCCESS;
        }
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }


    /**
     * 用户作品添加
     *
     * @return
     */
    @Action(value = "/user/product/save", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String userSave() {
        Object userId = session.get("user");
        if (userId == null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_no_login");
            return SUCCESS;
        }

        User user = userService.getById(User.class, Long.parseLong(userId.toString()));
        if (user == null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_not_exist");
            return SUCCESS;
        }
        Long id = product.getId();
        //去除前端传过来的连接的"前缀引号
        product.setSbimage(product.getSbimage().replace("\"",""));
        product.setSburl(product.getSburl().replace("\"",""));

        Product oldProduct = null;
        //判断需要再次生成二维码url
        Boolean flag= false;
        if (id != null) {
            oldProduct = productService.getById(Product.class, id);
            if(!oldProduct.getSburl().equals(product.getSburl())){
                flag = true;
            }
        }
        if (oldProduct == null) {
            oldProduct = new Product();
            //设置默认值
            oldProduct.setCreateTime(new Date());
            oldProduct.setType(2);
            oldProduct.setShowProduct(0);
            oldProduct.setShowOrder(1);
            oldProduct.setAuthor(user.getNickName());
            oldProduct.setAuthorId(user.getId());
            flag = true;
        }
        BeanCopyUtil.copyProperties(product, oldProduct, true);
        if(flag){
            createQRCode(oldProduct);
        }
        productService.save(oldProduct);
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }


    /**
     * 用户作品删除
     *
     * @return
     */
    @Action(value = "/user/product/delete", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String userDelete() {
        Object userId = session.get("user");
        if (userId == null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_no_login");
            return SUCCESS;
        }
        Long id = product.getId();
        if (id == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Product oldProduct = productService.getById(Product.class, id);
        if (oldProduct == null || oldProduct.getAuthorId() != Long.parseLong(userId.toString())) {
            responseTool.setStatus(0);
            responseTool.setCode("product_not_exist");
            return SUCCESS;
        }
        productService.delete(oldProduct);
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }


    /**
     * 分页 用户作品
     *
     * @return
     */
    @Action(value = "/user/product/page", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "page",
            "includeProperties", "pageNo,pageSize,totalCount,result\\[\\d+\\]\\.id,result\\[\\d+\\]\\.name,result\\[\\d+\\]\\.author,result\\[\\d+\\]\\.introduction,result\\[\\d+\\]\\.sbimage,result\\[\\d+\\]\\.createTime"
    })})
    public String userPage() {
        Object userId = session.get("user");
        Long authorId = Long.parseLong(userId.toString());
        Map<String, Object> args = new HashMap<>();
        if (authorId != null) {
            args.put("authorId", authorId);
        }
        if (page == null) {
            page = new Page<>();
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
        }
        productService.page(page, args);
        responseTool.setStatus(1);
        responseTool.setData(page);
        return SUCCESS;
    }


    /**
     * 用户查看
     *
     * @return
     */
    @Action(value = "/user/product/detail", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id,data\\.name,data\\.author,data\\.introduction,data\\.sbimage,data\\.sburl,data\\.ewmUrl,data\\.createTime"
    })})
    public String userDetail() {
        Object userId = session.get("user");
        Long id = product.getId();
        if (id == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Product oldProduct = productService.getById(Product.class, id);
        if (oldProduct == null || !oldProduct.getAuthorId().equals(Long.parseLong(userId.toString()))) {
            responseTool.setStatus(0);
            responseTool.setCode("product_not_exist");
            return SUCCESS;
        }
        responseTool.setStatus(1);
        responseTool.setData(oldProduct);
        return SUCCESS;
    }


    /**
     * 创建二维码
     * @param oldProduct
     */
    private void createQRCode(Product oldProduct){
        String fileName = getFileName();
        String filePath = getRootPath()+ File.separator + "upload" + File.separator + "qrcode" + File.separator + fileName;
        String qrCodeUrl = getQRCodeURL()+"upload/qrcode/"+fileName;
        File saveFile = new File(filePath);
        if (!saveFile.getParentFile().exists()) {
            if (!saveFile.getParentFile().mkdirs()) {
                responseTool.setStatus(0);
                responseTool.setCode("upload_fail");
                return ;
            }
        }
        try {
            QRCodeUtil.createQRCode(qrCodeUrl,filePath);
            oldProduct.setEwmUrl(qrCodeUrl);
        } catch (WriterException e) {
            log.info("二维码保存失败");
        } catch (IOException e) {
            log.info("打开文件失败");
        }
    }

    /**
     * 获取服务器根路径
     *
     * @return
     */
    private String getRootPath() {
        return ServletActionContext.getServletContext().getRealPath(File.separator);
    }

    /**
     * 获取二维码图片名称
     *
     * @return
     */
    private String getFileName() {
        return DateUtils.getDateString(new Date()) + UUID.randomUUID().toString().substring(0, 4) + ".png";
    }

    /**
     * 获取二维码url前缀
     * @return
     */
    private String getQRCodeURL() {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
    }

    @Override
    public Product getModel() {
        if (product == null) {
            product = new Product();
        }
        return product;
    }

    public Page<Product> getPage() {
        return page;
    }

    public void setPage(Page<Product> page) {
        this.page = page;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }
}
